package com.hc.appanimal;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Locale;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.hc.DTO.MessageDTO;
import com.hc.DTO.TokenDTO;
import com.hc.adapter.MessagesAdapter;
import com.hc.constants.Constants;
import com.hc.model.utils.MessageModel;
import com.hc.model.utils.TokenModel;
import com.hc.webservice.InternetUtils;
import com.nostra13.universalimageloader.core.ImageLoader;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ViewMessageActivity extends Activity implements OnClickListener,
		OnItemClickListener {
	Dialog dialog;
	AnimationDrawable frameAnimation;
	Button btnBack;
	TextView txtTitle;
	ListView lvMessage;
	MessagesAdapter adapter;
	ArrayList<Object> arrData;
	ArrayList<MessageDTO> arrMess;
	ImageView img_view_push_messages, img_new_push_message, contact_us, update;
	boolean flag = false;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_view_message);

		// new VerySlowTask().execute();

		btnBack = (Button) findViewById(R.id.btnBack);
		btnBack.setVisibility(View.VISIBLE);
		btnBack.setOnClickListener(this);
		txtTitle = (TextView) findViewById(R.id.txtTitle);
		txtTitle.setText("List Messages");
		txtTitle.setTextSize(15.0f);
		lvMessage = (ListView) findViewById(R.id.lvMessage);
		arrData = new ArrayList<Object>();
		adapter = new MessagesAdapter(this, R.layout.row_list_message, arrData);
		lvMessage.setAdapter(adapter);
		arrMess = new ArrayList<MessageDTO>();
		lvMessage.setOnItemClickListener(this);

		img_view_push_messages = (ImageView) findViewById(R.id.img_view_push_messages);
		img_new_push_message = (ImageView) findViewById(R.id.img_new_push_message);
		contact_us = (ImageView) findViewById(R.id.contact_us);
		update = (ImageView) findViewById(R.id.update);
		img_view_push_messages.setOnClickListener(this);
		img_new_push_message.setOnClickListener(this);
		contact_us.setOnClickListener(this);
		update.setOnClickListener(this);
		txtTitle = (TextView) findViewById(R.id.txtTitle);
		txtTitle.setText("Messages");
		// Collections.sort(arrData, objComparator);
		new VerySlowTask().execute();
		MessageModel modelMess = MessageModel.getInstance();
		MessageDTO messDTO = modelMess.getMessage(ViewMessageActivity.this);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String currentDay = sdf.format(new Date());
		if (messDTO.getDatemessage().equalsIgnoreCase(currentDay)) {
			img_view_push_messages
					.setImageResource(R.drawable.view_push_messages_new1);
		}
		img_new_push_message.setBackgroundResource(R.drawable.new_push_message);
		contact_us.setBackgroundResource(R.drawable.contact_us);
	}

	public class VerySlowTask extends AsyncTask<Void, Void, Void> {
		TokenModel tokenModel = TokenModel.getInstance();
		TokenDTO token = tokenModel.getToken(ViewMessageActivity.this);
		String t = "";
		boolean flag = false;

		public VerySlowTask() {
			dialog = new Dialog(ViewMessageActivity.this, R.style.NewDialog);
			dialog.setContentView(R.layout.loading);

			dialog.setCancelable(false);
			dialog.findViewById(R.id.loading_icon).setBackgroundResource(
					R.drawable.spin_animation);
			frameAnimation = (AnimationDrawable) dialog.findViewById(
					R.id.loading_icon).getBackground();
			dialog.show();
			frameAnimation.start();
		}

		@Override
		protected Void doInBackground(Void... params) {
			HttpEntity httpEntity = null;
			HttpClient client = new DefaultHttpClient();
			HttpGet method = new HttpGet(Constants.URL_GET_ALL_PUSH_DATA);
			method.setHeader("Content-Type",
					"application/x-www-form-urlencoded;charset=UTF-8");
			method.setHeader("Authorization", token.getToken_type() + " "
					+ token.getAccess_token());

			HttpResponse response;
			try {
				response = client.execute(method);
				httpEntity = response.getEntity();
				BufferedReader br = new BufferedReader(new InputStreamReader(
						(response.getEntity().getContent())));
				String output;
				System.out.println("Output from Server .... \n");
				StringBuilder builder = new StringBuilder();
				while ((output = br.readLine()) != null) {
					System.out.println(output);
					builder.append(output);
				}
				
				String strJson = builder.toString();

				if (strJson != null) {
					JSONArray jsonArr = new JSONArray(strJson);
					for (int i = jsonArr.length() - 1; i >= 0; i--) {
						JSONObject obj = jsonArr.getJSONObject(i);
						MessageDTO mesDTO = new MessageDTO();

						if (obj.has("DescExp")) {
							String DescExp = obj.getString("DescExp");
							mesDTO.setDescExp(DescExp);
						}
						if (obj.has("UpdatedOn")) {
							String UpdatedOn = obj.getString("UpdatedOn");
							mesDTO.setUpdatedOn(UpdatedOn);
						}
						if (obj.has("Description")) {
							String Description = obj.getString("Description");
							mesDTO.setDescription(Description);
						}

						JSONArray arrPushDataIs = obj
								.getJSONArray("PushDataIs");
						int dem = 0;
						ArrayList<String> pathImg = new ArrayList<String>();
						for (int j = 0; j < arrPushDataIs.length(); j++) {
							JSONObject jsonPushDataIs = arrPushDataIs
									.getJSONObject(j);

							if (jsonPushDataIs.has("FilePath")) {
								String FilePath = jsonPushDataIs
										.getString("FilePath");
								pathImg.add(FilePath);
								mesDTO.setFilePath(pathImg);
							}
							dem++;
						}
						if (dem > 0) {
							mesDTO.setCount(dem);
						}

						JSONObject objUser = obj.getJSONObject("User");

						if (objUser.has("FirstName")) {
							String FirstName = objUser.getString("FirstName");
							mesDTO.setFirstName(FirstName);
						}
						if (objUser.has("LastName")) {
							String LastName = objUser.getString("LastName");
							mesDTO.setLastName(LastName);
						}

						if (mesDTO != null) {
							arrData.add(mesDTO);
							arrMess.add(mesDTO);
						}

					}
				}
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				flag = true;
				e.printStackTrace();
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			dialog.dismiss();
			frameAnimation.stop();
			if (flag) {
				Intent intent = new Intent(ViewMessageActivity.this,
						LoginActivity.class);
				startActivity(intent);
				finish();
			} else {
				adapter.notifyDataSetChanged();
			}

		}

	}

	Comparator<Object> objComparator = new Comparator<Object>() {
		public int compare(Object o1, Object o2) {
			MessageDTO dto = (MessageDTO) o1;

			String date = dto.getUpdatedOn();
			String year = date.substring(0, 4);
			String mon = date.substring(5, 7);
			String day = date.substring(8, 10);
			String str1 = day + "-" + mon + "-" + year;
			MessageDTO dto2 = (MessageDTO) o2;
			String date1 = dto2.getUpdatedOn();

			String year1 = date1.substring(0, 4);
			String mon1 = date1.substring(5, 7);
			String day1 = date1.substring(8, 10);
			String str2 = day1 + "-" + mon1 + "-" + year1;
			return str1.compareTo(str2);
		}
	};

	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {

		case R.id.btnBack:
			finish();
			break;

		case R.id.img_new_push_message:
			intent = new Intent(ViewMessageActivity.this,
					UpdateAnimalActivity.class);
			startActivity(intent);
			finish();
			break;
		case R.id.contact_us:
			intent = new Intent(ViewMessageActivity.this,
					ContactUsActivity.class);
			startActivity(intent);
			finish();
			break;
		case R.id.update:
			TokenModel tokenModel = TokenModel.getInstance();
			TokenDTO tokenDTO = tokenModel.getToken(ViewMessageActivity.this);
			String dateExpires = tokenDTO.getExpires();
			Date date2 = null;
			Date date1 = null;
			String pattern = "EEE, dd MMM yyyy HH:mm:ss Z";
			SimpleDateFormat format = new SimpleDateFormat(pattern,
					Locale.ENGLISH);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String currentDay = sdf.format(new Date());
			String currentDayExpires = format.format(new Date());
			try {
				date1 = format.parse(currentDayExpires);
				date2 = format.parse(dateExpires);
				if (date1.compareTo(date2) < 0) {
					if (InternetUtils.getInstance()
							.isConnectingToInternet(this)) {
						this.runOnUiThread(new Runnable() {

							@Override
							public void run() {
								String path = Constants.URL_CATEGORY;
								String[] strs = path.split("/");
								File file = new File(Environment
										.getExternalStorageDirectory()
										+ "/"
										+ Constants.APP_NAME
										+ "/"
										+ strs[4]
										+ "/");
								// deleteDirectory(file);
								DeleteRecursive(file);

							}
						});
						new AsystaskUpdateAnimal(currentDay, tokenDTO,
								ViewMessageActivity.this).execute();
						flag = true;
						// arrData = new ArrayList<Object>();
						// InitData();
						// adapter = new AnimalCategoryMasterAdapter(this,
						// R.layout.grid_row,
						// arrData);

					} else {
						Toast.makeText(ViewMessageActivity.this, "no network",
								Toast.LENGTH_LONG).show();
					}
				}
			} catch (Exception e) {
				// TODO: handle exception
			}

			break;

		default:
			break;
		}

	}
	private void DeleteRecursive(File fileOrDirectory) {
	    if (fileOrDirectory.isDirectory())
	        for (File child : fileOrDirectory.listFiles())
	        {
	            child.delete();
	            DeleteRecursive(child);
	        }

	    fileOrDirectory.delete();
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		MessageModel modelMess = MessageModel.getInstance();
		MessageDTO messDTO = modelMess.getMessage(ViewMessageActivity.this);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String currentDay = sdf.format(new Date());
		if (messDTO.getDatemessage().equalsIgnoreCase(currentDay)) {
			img_view_push_messages
					.setImageResource(R.drawable.view_push_messages_new1);
		}
		if(flag){
			ImageLoader.getInstance().clearDiskCache();
			ImageLoader.getInstance()
					.clearMemoryCache();
			flag = false;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		MessageDTO mess = (MessageDTO) lvMessage.getItemAtPosition(position);
		Intent intent = new Intent(ViewMessageActivity.this,
				DetailMessagesActivity.class);

		Bundle data = new Bundle();
		data.putSerializable("detailmess", mess);
		data.putInt("key", 2);
		intent.putExtras(data);
		startActivity(intent);
	}

}
